#!/bin/bash

# 高效文件扫描器 - Linux构建脚本
# 版本: 1.0

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未找到，请先安装"
        return 1
    fi
    return 0
}

# 检查依赖
check_dependencies() {
    print_info "检查构建依赖..."
    
    local missing_deps=()
    
    if ! check_command cmake; then
        missing_deps+=("cmake")
    fi
    
    if ! check_command make; then
        missing_deps+=("make")
    fi
    
    if ! check_command g++; then
        missing_deps+=("g++")
    fi
    
    # 检查Qt5
    if ! pkg-config --exists Qt5Core Qt5Widgets; then
        missing_deps+=("qt5-default qtbase5-dev")
    fi
    
    if [ ${#missing_deps[@]} -ne 0 ]; then
        print_error "缺少以下依赖: ${missing_deps[*]}"
        print_info "请运行以下命令安装依赖:"
        print_info "Ubuntu/Debian: sudo apt install build-essential cmake qt5-default qtbase5-dev"
        print_info "CentOS/RHEL: sudo yum install gcc-c++ cmake qt5-qtbase-devel"
        print_info "Arch Linux: sudo pacman -S base-devel cmake qt5-base"
        exit 1
    fi
    
    print_success "所有依赖检查通过"
}

# 清理构建目录
clean_build() {
    if [ -d "build" ]; then
        print_info "清理旧的构建目录..."
        rm -rf build
    fi
}

# 创建构建目录
create_build_dir() {
    print_info "创建构建目录..."
    mkdir -p build
    cd build
}

# 配置项目
configure_project() {
    print_info "配置CMake项目..."
    
    local build_type=${1:-Release}
    local qt_path=""
    
    # 尝试自动找到Qt5路径
    if [ -n "$CMAKE_PREFIX_PATH" ]; then
        qt_path="-DCMAKE_PREFIX_PATH=$CMAKE_PREFIX_PATH"
    elif [ -d "/usr/lib/x86_64-linux-gnu/cmake/Qt5" ]; then
        qt_path="-DCMAKE_PREFIX_PATH=/usr/lib/x86_64-linux-gnu/cmake/Qt5"
    elif [ -d "/usr/lib64/cmake/Qt5" ]; then
        qt_path="-DCMAKE_PREFIX_PATH=/usr/lib64/cmake/Qt5"
    fi
    
    cmake .. \
        -DCMAKE_BUILD_TYPE=$build_type \
        -DCMAKE_INSTALL_PREFIX=../install \
        $qt_path
    
    if [ $? -eq 0 ]; then
        print_success "CMake配置成功"
    else
        print_error "CMake配置失败"
        exit 1
    fi
}

# 编译项目
build_project() {
    print_info "开始编译项目..."
    
    local jobs=$(nproc)
    print_info "使用 $jobs 个并行任务进行编译"
    
    make -j$jobs
    
    if [ $? -eq 0 ]; then
        print_success "编译成功"
    else
        print_error "编译失败"
        exit 1
    fi
}

# 安装项目
install_project() {
    print_info "安装项目文件..."
    
    make install
    
    if [ $? -eq 0 ]; then
        print_success "安装成功"
    else
        print_error "安装失败"
        exit 1
    fi
}

# 运行测试
run_tests() {
    print_info "运行基本测试..."
    
    # 检查DLL是否生成
    if [ -f "lib/libFileScanner.so" ]; then
        print_success "DLL模块生成成功: lib/libFileScanner.so"
    else
        print_error "DLL模块生成失败"
        return 1
    fi
    
    # 检查UI程序是否生成
    if [ -f "bin/FileScannerUI" ]; then
        print_success "UI程序生成成功: bin/FileScannerUI"
    else
        print_error "UI程序生成失败"
        return 1
    fi
    
    # 检查依赖
    print_info "检查程序依赖..."
    ldd bin/FileScannerUI | grep -E "(Qt5|libFileScanner)" || true
    
    print_success "所有测试通过"
}

# 创建运行脚本
create_run_script() {
    print_info "创建运行脚本..."
    
    cat > run_scanner.sh << 'EOF'
#!/bin/bash

# 设置库路径
export LD_LIBRARY_PATH="$(dirname "$0")/lib:$LD_LIBRARY_PATH"

# 运行程序
cd "$(dirname "$0")"
./bin/FileScannerUI "$@"
EOF

    chmod +x run_scanner.sh
    print_success "运行脚本创建成功: run_scanner.sh"
}

# 显示使用说明
show_usage() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示此帮助信息"
    echo "  -c, --clean    清理构建目录"
    echo "  -d, --debug    编译调试版本"
    echo "  -r, --release  编译发布版本 (默认)"
    echo "  -t, --test     运行测试"
    echo "  -i, --install  安装到系统"
    echo "  --run          编译后立即运行"
    echo ""
    echo "示例:"
    echo "  $0                # 编译发布版本"
    echo "  $0 -d             # 编译调试版本"
    echo "  $0 -c -r          # 清理后编译发布版本"
    echo "  $0 --run          # 编译并运行"
}

# 主函数
main() {
    local build_type="Release"
    local clean_first=false
    local run_tests_flag=false
    local install_flag=false
    local run_after_build=false
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_usage
                exit 0
                ;;
            -c|--clean)
                clean_first=true
                shift
                ;;
            -d|--debug)
                build_type="Debug"
                shift
                ;;
            -r|--release)
                build_type="Release"
                shift
                ;;
            -t|--test)
                run_tests_flag=true
                shift
                ;;
            -i|--install)
                install_flag=true
                shift
                ;;
            --run)
                run_after_build=true
                shift
                ;;
            *)
                print_error "未知选项: $1"
                show_usage
                exit 1
                ;;
        esac
    done
    
    print_info "开始构建高效文件扫描器项目..."
    print_info "构建类型: $build_type"
    
    # 检查依赖
    check_dependencies
    
    # 清理构建目录（如果需要）
    if [ "$clean_first" = true ]; then
        clean_build
    fi
    
    # 创建构建目录
    create_build_dir
    
    # 配置项目
    configure_project $build_type
    
    # 编译项目
    build_project
    
    # 运行测试（如果需要）
    if [ "$run_tests_flag" = true ]; then
        run_tests
    fi
    
    # 安装项目（如果需要）
    if [ "$install_flag" = true ]; then
        install_project
    fi
    
    # 创建运行脚本
    create_run_script
    
    # 返回项目根目录
    cd ..
    
    print_success "构建完成！"
    print_info "构建输出位于: build/"
    print_info "运行程序: cd build && ./run_scanner.sh"
    
    # 立即运行（如果需要）
    if [ "$run_after_build" = true ]; then
        print_info "启动程序..."
        cd build
        ./run_scanner.sh &
        cd ..
    fi
}

# 脚本入口点
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi